import { Card, CardBody, CardHeader, Input, Button, Pagination } from "@heroui/react";
import { useState, useMemo } from "react";
import { SearchIcon, EyeIcon, PencilIcon, TrashIcon } from "@/components/icons";
import DefaultLayout from "@/layouts/default";

export default function TablePage() {
  // Mock data for the table
  const mockData = [
    { id: 1, name: "张三", email: "zhangsan@example.com", role: "管理员", status: "活跃" },
    { id: 2, name: "李四", email: "lisi@example.com", role: "编辑", status: "活跃" },
    { id: 3, name: "王五", email: "wangwu@example.com", role: "用户", status: "非活跃" },
    { id: 4, name: "赵六", email: "zhaoliu@example.com", role: "编辑", status: "活跃" },
    { id: 5, name: "孙七", email: "sunqi@example.com", role: "用户", status: "活跃" },
    { id: 6, name: "周八", email: "zhouba@example.com", role: "管理员", status: "非活跃" },
    { id: 7, name: "吴九", email: "wujiu@example.com", role: "用户", status: "活跃" },
    { id: 8, name: "郑十", email: "zhengshi@example.com", role: "编辑", status: "非活跃" },
    { id: 9, name: "王十一", email: "wangshiyi@example.com", role: "用户", status: "活跃" },
    { id: 10, name: "李十二", email: "lishier@example.com", role: "管理员", status: "活跃" },
    { id: 11, name: "张十三", email: "zhangsanshi@example.com", role: "编辑", status: "非活跃" },
    { id: 12, name: "赵十四", email: "zhaoshisi@example.com", role: "用户", status: "活跃" },
  ];

  const [searchTerm, setSearchTerm] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 5;

  // Filter data based on search term
  const filteredData = useMemo(() => {
    if (!searchTerm) return mockData;
    return mockData.filter(item => 
      item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.role.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [searchTerm]);

  // Pagination logic
  const totalPages = Math.ceil(filteredData.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const paginatedData = filteredData.slice(startIndex, startIndex + itemsPerPage);

  // Handle page change
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  // Handle search input change
  const handleSearchChange = (value: string) => {
    setSearchTerm(value);
    setCurrentPage(1); // Reset to first page when searching
  };

  // Handle view action
  const handleView = (id: number) => {
    console.log("View item with id:", id);
    // Implement view logic here
  };

  // Handle edit action
  const handleEdit = (id: number) => {
    console.log("Edit item with id:", id);
    // Implement edit logic here
  };

  // Handle delete action
  const handleDelete = (id: number) => {
    console.log("Delete item with id:", id);
    // Implement delete logic here
  };

  return (
    <DefaultLayout>
      <div className="flex flex-col gap-6 py-6">
        {/* Page Title */}
        <div className="flex flex-col gap-2">
          <h1 className="text-2xl font-bold">用户管理</h1>
          <p className="text-default-500">管理系统中的用户信息</p>
        </div>

        {/* Search and Controls */}
        <Card className="shadow-sm">
          <CardBody>
            <div className="flex flex-col md:flex-row justify-between gap-4">
              <div className="w-full md:w-1/3">
                <Input
                  placeholder="搜索用户..."
                  startContent={<SearchIcon className="text-default-400" />}
                  value={searchTerm}
                  onChange={(e) => handleSearchChange(e.target.value)}
                />
              </div>
              <div className="flex gap-2">
                <Button color="primary">添加用户</Button>
              </div>
            </div>
          </CardBody>
        </Card>

        {/* Table */}
        <Card className="shadow-sm">
          <CardHeader>
            <h2 className="text-lg font-semibold">用户列表</h2>
          </CardHeader>
          <CardBody>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-default-200">
                    <th className="py-3 px-4 text-left">ID</th>
                    <th className="py-3 px-4 text-left">姓名</th>
                    <th className="py-3 px-4 text-left">邮箱</th>
                    <th className="py-3 px-4 text-left">角色</th>
                    <th className="py-3 px-4 text-left">状态</th>
                    <th className="py-3 px-4 text-right">操作</th>
                  </tr>
                </thead>
                <tbody>
                  {paginatedData.length > 0 ? (
                    paginatedData.map((item) => (
                      <tr key={item.id} className="border-b border-default-100 hover:bg-default-50">
                        <td className="py-3 px-4">{item.id}</td>
                        <td className="py-3 px-4 font-medium">{item.name}</td>
                        <td className="py-3 px-4">{item.email}</td>
                        <td className="py-3 px-4">
                          <span className="px-2 py-1 rounded-full text-xs bg-primary/10 text-primary">
                            {item.role}
                          </span>
                        </td>
                        <td className="py-3 px-4">
                          <span className={`px-2 py-1 rounded-full text-xs ${
                            item.status === "活跃" 
                              ? "bg-success/10 text-success" 
                              : "bg-warning/10 text-warning"
                          }`}>
                            {item.status}
                          </span>
                        </td>
                        <td className="py-3 px-4">
                          <div className="flex justify-end gap-2">
                            <Button 
                              isIconOnly 
                              size="sm" 
                              variant="light"
                              onPress={() => handleView(item.id)}
                            >
                              <EyeIcon className="w-4 h-4" />
                            </Button>
                            <Button 
                              isIconOnly 
                              size="sm" 
                              variant="light"
                              onPress={() => handleEdit(item.id)}
                            >
                              <PencilIcon className="w-4 h-4" />
                            </Button>
                            <Button 
                              isIconOnly 
                              size="sm" 
                              variant="light"
                              color="danger"
                              onPress={() => handleDelete(item.id)}
                            >
                              <TrashIcon className="w-4 h-4" />
                            </Button>
                          </div>
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td colSpan={6} className="py-6 px-4 text-center text-default-500">
                        没有找到匹配的用户
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>

            {/* Pagination */}
            {filteredData.length > 0 && (
              <div className="flex justify-between items-center py-4">
                <p className="text-default-500 text-sm">
                  显示第 {startIndex + 1} 到 {Math.min(startIndex + itemsPerPage, filteredData.length)} 条，
                  共 {filteredData.length} 条记录
                </p>
                <Pagination
                  total={totalPages}
                  initialPage={1}
                  page={currentPage}
                  onChange={handlePageChange}
                />
              </div>
            )}
          </CardBody>
        </Card>
      </div>
    </DefaultLayout>
  );
}